import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {HttpClient} from '@angular/common/http';

import {Router} from '@angular/router';
import { CustomerConfigService } from '@app/core/public-api';
@Component({
  selector: 'app-select-user',
  templateUrl: './select-user.component.html',
  styleUrls: ['./select-user.component.scss']
})
 
export class SelectUserComponent implements OnInit {

  orgData: { key: string, value: string }[] = [];
  selectedValue: string = '';
  usertoken : string = '' ;
  constructor(private route: ActivatedRoute, private http: HttpClient, private router: Router,
    private customerConfigService :CustomerConfigService)  {
      
  }

  ngOnInit() {
    this.route.queryParams.subscribe(params => {
      
      this.usertoken = params['usertoken'];
      if (!this.usertoken) {
        alert("当前用户无对应处理中心租户，请联系管理员！");
        window.location.href = '/login';
        return;
      }

      const url = '/customerConfigData';
      const postData = { username: this.usertoken };
      this.http.post<any>(url, postData).subscribe(
        data => this.handleOnInitSuccessResponse(data),
        error => this.handleOnInitErrorResponse(error)
      );
    });
  }

  onSubmit({ key: selectedValue }: { key: string, value: string }) {
    
    const postData = { username: selectedValue, oldName: this.usertoken };
   const customerConfig= this.customerConfig.filter(i=>i.orgUser==postData.username)[0]
this.customerConfigService.setConfig(customerConfig);
console.log(this.customerConfig)
    this.http.post<any>('/sendValue', postData).subscribe(
      response => this.handleOnSubmitSuccessResponse(response),
      error => this.handleOnSubmitErrorResponse(error)
    );
  }

  handleOnSubmitSuccessResponse(response: any) {
    
    const redirectUrl = response.redirectUrl;
    window.location.href = redirectUrl;  
      //this.router.navigate(redirectUrl);
  }

  handleOnSubmitErrorResponse(error: any) {
    console.error('Error submitting data:', error);
    
    // alert("您选择的用户不存在！");
    window.location.href = '/login';
  }

  customerConfig;
  handleOnInitSuccessResponse(data: any) {
    
   // const userName = data.oldName;
   this.customerConfig=data.config
    const dataFromBackend = data.orgUserAndOrgName.split(',');
    this.orgData = dataFromBackend.map(item => {
      const [key, value] = item.split(':');
      return { key, value };
    });
  }

  handleOnInitErrorResponse(error: any) {
    console.error('Error submitting data:', error);
    
    // alert("您选择的用户不存在！");
    window.location.href = '/login';

  }
}

